<?php

namespace Base\Mail;

use Zend\Mail\Transport\Smtp as SmtpTransport;
use Zend\Mail\Message;

use Zend\View\Model\ViewModel;

use Zend\Mime\Message as MimeMessage;
use Zend\Mime\Part as MimePart;

class Mail {
	
	/**
	 * transport
	 * @var string
	 */
	protected $transport;
	
	/**
	 * view <HTML>
	 * @var html
	 */
	protected $view;
	
	/**
	 * Corpo da mensagem
	 * @var string
	 */
	protected $body;
	
	/**
	 * mensagem do email
	 * @var string
	 */
	protected $message;
	
	/**
	 * Assunto da mensagem
	 * @var string
	 */
	protected $subject;
	
	/**
	 * Para quem
	 * @var string
	 */
	protected $to;
	
	/**
	 * Array de dados
	 * @var array
	 */
	protected $data;
	
	/**
	 * nome da página
	 * @var string
	 */
	protected $page;
	
	
	/**
	 * __construct
	 * @param SmtpTransport $transport
	 * @param HTML $view
	 * @param string $page
	 */
	public function __construct(SmtpTransport $transport, $view, $page) {
		
		$this->transport = $transport;
		$this->view = $view;
		$this->page = $page;
		
	}

	/**
	 * @param string $subject
	 */
	public function setSubject($subject) {
		
		$this->subject = $subject;
		return $this;
		
	}

	/**
	 * @param string $to
	 */
	public function setTo($to) {
		
		$this->to = $to;
		return $this;
		
	}

	/**
	 * @param array $data
	 */
	public function setData($data) {
		
		$this->data = $data;
		return $this;
	}
	
	/**
	 * @method renderView()
	 * Método utilizado para renderizar a view
	 * @param string $page
	 * @param array $data
	 */
	public function renderView($page, array $data) {
		
		$model = new ViewModel();
		$model->setTemplate("mailer/{$page}.phtml");
		$model->setOption('has_parent', true);
		$model->setVariables($data);
		
		return $this->view->render($model);
		
	}

	/**
	 * @method prepare()
	 * Prepara o email para o envio, arquivos HTML, transport, etc...
	 * @return Mail 
	 */
	public function prepare() {
		
		$html = new MimePart($this->renderView($this->page, $this->data));
		$html->type = 'text/html';
		
		$body = new MimeMessage();
		$body->setParts(array($html));
		$this->body = $body;
		
		$config = $this->transport->getOptions()->toArray();
		
		$this->message = new Message();
		$this->message->addFrom($config['connection_config']['from'])
			->addTo($this->to)
			->setSubject($this->subject)
			->setBody($this->body);
		
		return $this;
		
	}
	
	/**
	 * @method send()
	 * Envia o email
	 */
	public function send() {
		
		$this->transport->send($this->message);
		
	}
	
}